<?php
namespace core;


class Route {
    private string $group; //分组
    private string $nsParent; //父命名空间
    private string $ns = ''; //分组命名空间
    private array $routes = []; //分组下的路由, 包括分组
    private array $middlewares; //分组中间件


    public function __construct(string $group, string $nsParent = '', array $middlewares = []) {
        $this->group = $group;
        $this->nsParent = $nsParent;
        $this->middlewares = $middlewares;
    }


    public function getGroup(): string {
        return $this->group;
    }

    public function getNamespace(): string {
        if (!$this->nsParent && !$this->ns) return APP_CONTROLLER_NAMESPACE;

        if ($this->ns) return $this->ns;
        if ($this->nsParent) return $this->nsParent;

        return '';
    }

    public function setNamespace(string $ns): void {
        $this->ns = $ns;
    }

    public function getRoutes(): array {
        return $this->routes;
    }

    public function addRoute(string $method, string $uri, \Closure | string $cb, $middleware): void {
        $method = strtoupper($method);
        slash_add($uri);

        $middlewares = [];
        if ($middleware && is_array($middleware)) {
            $middlewares = $middleware;
        } else if ($middleware) {
            $middlewares[] = $middleware;
        }

        $item = new RouteItem($method, $uri, $cb, $middlewares);

        $this->routes[] = $item;
    }

    public function addChild(Route $child): void {
        $this->routes[] = $child;
    }

    public function getMiddlewares(): array {
        return $this->middlewares;
    }

    public function addMiddleware(array | string $middleware): void {
        if (is_array($middleware)) {
            $this->middlewares = array_merge($this->middlewares, $middleware);
        } else {
            $this->middlewares[] = $middleware;
        }
    }
}
